package org.gitman.agent.platform;

import java.awt.Color;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

import com.mxgraph.model.mxCell;


public class AgentManager {

	private List<Agent> agents;
	private Queue<Agent> agents2serve;
	private AddedAgentInfo info;
	private PlatformManager platformManager;
	
	public AgentManager(PlatformManager platformManager){
		this.platformManager = platformManager;
		agents = new LinkedList<Agent>();
	}
	
	public List<Agent> getAgents() {
		return agents;
	}
	
	public void addAgent(Agent agent){
		agents.add(agent);
		platformManager.getMainFrame().getSimulationPanel().updateAgentsTab();
	}

	/**
	 * this method add agent to global list
	 * @param agent
	 */
	public void removeAgent(Agent agent) {
		agents.remove(agent);
	}
	
	public void setAddedAgentInfo(AddedAgentInfo info) {
		this.info = info;
	}
	
	public AddedAgentInfo getAddedAgentInfo(){
		return info;
	}
	
	/**
	 * this method initialize simulation agent queue
	 */
	public void initializeAgentQueue() {
		agents2serve = new LinkedList<Agent>();
		for(Agent a : agents){
			a.setCurrentPoint(a.getStartPoint());
			a.setIteration(0);
			if(!a.reachTarget()){
				agents2serve.add(a);
				a.setState(AgentState.working);
			}else{
				a.setState(AgentState.done);
			}
		}
	}
	
	/**
	 * this method returns next agnet in simulation queue, only agent that are not already in place are in this queue
	 * @return
	 */
	public Agent nextAgent(){
		return agents2serve.poll();
	}

	/**
	 * this method adds agent to simulation queue (shouldn't be used from gui)
	 * @param agent
	 */
	public void addAgent2Queue(Agent agent){
		agents2serve.add(agent);
	}

	/**
	 * this method returns all agents in simulation queue
	 * @return
	 */
	public Collection<Agent> getAllAgentsInQueue(){
		return agents2serve;
	}

	/**
	 * this method is used to broadcast messages
	 * @param message
	 * @param sender
	 */
	public void broadCastMessage(Object message, Agent sender){
		for(Agent a : agents2serve){
			if(!a.equals(sender)){
				a.handleMessage(message, sender);
			}
		}
	}

	/**
	 * determinate if give color is not already used in platform
	 * @param c
	 * @return
	 */
	public boolean isColorOk(Color c) {
		for(Agent a : agents){
			if(a.getColor().getBlue() == c.getBlue()){
				return false;
			}
		}
		return true;
	}

	
	/**
	 * this method returns true only if none other agent have the same start point
	 * @param startPoint
	 * @return
	 */
	public boolean isStartPointOk(mxCell startPoint) {
		String id = startPoint.getId();
		for(Agent agent : agents){
			if(agent.getStartPoint().getId().equals(id)){
				return false;
			}
		}
		return true;
	}
}
